﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace TheCup.ApiControllers
{
    public class StatController : ApiController
    {
        // Average stats for a Player
        // GET: api/Stat/5
        public IEnumerable<AvgStats> GetByPlayer(int playerid)
        {
            using (var ctx = new TheCupContext())
            {
                var scores = (from s in ctx.Scorecards
                              join r in ctx.Rounds on s.RoundId equals r.Id
                              select new  { year = r.DateEntry.Year, pid = s.PlayerId, putts = s.DbPutts, strokes = s.DbStrokes }).ToList();

                var grouped = scores.GroupBy(x => x.year, (date, value) => new AvgStats
                {
                    year = date,
                    putts = value.Where(x=>x.pid == playerid).Average(x => x.putts),
                    avgputts = value.Average(x => x.putts),
                    strokes = value.Where(x=>x.pid ==playerid).Average(x => x.strokes),
                    avgstrokes = value.Average(x => x.strokes)
                }).OrderBy(x => x.year);
                
                return grouped;
            }
        }

        // Average stats for a Course
        // GET: api/Stat/5
        public IEnumerable<AvgStats> GetByCourse(int courseid)
        {
            using (var ctx = new TheCupContext())
            {
                var scores = (from s in ctx.Scorecards
                              join r in ctx.Rounds on s.RoundId equals r.Id
                              select new { year = r.DateEntry.Year, cid = r.CourseId, putts = s.DbPutts, strokes = s.DbStrokes }).ToList();

                var grouped = scores.Where(x => x.cid == courseid).GroupBy(x => x.year, (date, value) => new AvgStats
                {
                    year = date,
                    //putts = value.Where(x => x.cid == courseid).Average(x => x.putts),
                    avgputts = value.Average(x => x.putts),
                    //strokes = value.Where(x => x.cid == courseid).Average(x => x.strokes),
                    avgstrokes = value.Average(x => x.strokes)
                }).OrderBy(x => x.year);

                return grouped;
            }
        }
    }
}
